﻿// -----------------------------------------------------------------------
// <copyright file="OkClickCommand.cs" company="">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace ModuleCustomerEdit.Commands
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows.Input;
    using ServerConnection.ShopServiceReference;
using Microsoft.Practices.Prism.Events;
    using Microsoft.Practices.Prism.Regions;
    using ModuleCustomer.View;
    using Microsoft.Practices.ServiceLocation;
    using ShellInfrastructure;
    using System.Text.RegularExpressions;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class OkClickCommand : ICommand
    {

        public event EventHandler CanExecuteChanged;

        private bool isEmail(string inputEmail)
        {
            bool result = false;

            if (!String.IsNullOrWhiteSpace(inputEmail))
            {
                string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                      @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                      @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
                Regex re = new Regex(strRegex);
                result = re.IsMatch(inputEmail);
            }

            return result;
        }

        public OkClickCommand()
        {
        }

        public bool CanExecute(object parameter)
        {
            bool result = true;

            User obj = (User)parameter;

            if (result)
            {
                result &= !String.IsNullOrWhiteSpace(obj.FIO);
                result &= !String.IsNullOrWhiteSpace(obj.Login);
                result &= !String.IsNullOrWhiteSpace(obj.Password) || (obj.Id != 0);
                result &= !String.IsNullOrWhiteSpace(obj.Phone);
                result &= String.IsNullOrWhiteSpace(obj.Email) || (this.isEmail(obj.Email));
            }

            return result;
        }

        public void Execute(object parameter)
        {

            User result = ServerConnection.Service.Instance.SetUser((User)parameter);

            if (result.Role == UserRole.Guest)
            {
                IRegionManager RegionManager = ServiceLocator.Current.GetInstance<IRegionManager>();

                IRegion region1 = RegionManager.Regions[RegionNames.LeftRegionName];
                ICustomerViewList obj1 = ServiceLocator.Current.GetInstance<ICustomerViewList>();
                obj1.Refresh();
            }
            else
            {
                throw new Exception("We have one with the same login-password pair!");
            }
        }
    }
}
